import { asyncRouterMap, constantRouterMap, noPageRoute } from '@/router'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(arr, route) {
  if (route.name && arr.indexOf(route.name) != -1) {
    return true
  }
  return false
}

/**
 * 递归过滤异步路由表，返回符合用户权限的路由表
 * @param routes asyncRouterMap
 * @param arr 用户有权限的 routeNames Array
 */
function filterAsyncRouter(routes, menus) {
  const res = []
  const arr = Object.keys(menus)
  routes.forEach(route => {
    const tmp = { ...route }
    if (!tmp.meta) tmp.meta = {}
    if (tmp.children) {
      tmp.children = filterAsyncRouter(tmp.children, menus)
      if (tmp.children.length > 0) {
        if (!tmp.meta) tmp.meta = {}
        tmp.meta.title = menus[tmp.name]
        res.push(tmp)
      }
    } else if (hasPermission(arr, tmp)) {
      tmp.meta.title = menus[tmp.name]
      res.push(tmp)
    }
  })
  return res
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    userPermissions: [],
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_USERPERMISSIONS: (state, permissions) => {
      state.userPermissions = permissions
    },
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menu } = data
        const routeNameList = {}
        const permissions = []
        menu.forEach(i => {
          if (i.resource_type != 'MENU') {
            routeNameList[i.target] = i.title
          }
          // 配置permissions数组
          i.power_codes = i.power_codes ? i.power_codes.split(',') : []
          i.power_codes.forEach(j => {
            permissions.push(`${i.target}.${j}`)
          })
        })
        let accessedRouters = []
        accessedRouters = filterAsyncRouter(asyncRouterMap, routeNameList)
        accessedRouters.push(noPageRoute)
        commit('SET_ROUTERS', accessedRouters)
        commit('SET_USERPERMISSIONS', permissions)
        resolve()
      })
    },
  },
  getters: {
    permission_routers: state => state.routers,
    addRouters: state => state.addRouters,
  },
}

export default permission
